﻿using log4net;
using NPOI.SS.UserModel;
using Quartz;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using YnBaseClass2;
using YnPlcDataServer.Entities;
using YnPlcDataServer.Scheduler;
using YnPlcDataServer.Utils;
using YnPlcDataServer.Variable;

namespace YnPlcDataServer
{
    public partial class MainForm : Form
    {
        #region 定义变量
        //日志
        private static readonly ILog logger = LogManager.GetLogger(typeof(MainForm));
        #endregion

       
        #region 主窗体
        public MainForm()
        {
            InitializeComponent();
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            //SQLiteHelper.AddHistoryData(1, "1.234");

            logger.Info("载入主窗体");

            // 日志显示
            Action<ListBox, object> AddLog = (ListBox lstBox, object message) =>
            {
                if (lstBox.Items.Count >= 500)
                    lstBox.Items.RemoveAt(0);

                lstBox.Items.Add(message);
                //lstBox.TopIndex = lstBox.Items.Count - (int)(lstBox.Height / lstBox.ItemHeight);
                lstBox.SelectedIndex = lstBox.Items.Count - 1;
            };
            Action<ListBox, object> ShowLog = (ListBox lstBox, object message) =>
            {
                if (lstBox.InvokeRequired)
                    lstBox.Invoke(new MethodInvoker(() => { AddLog(lstBox, message); }));
                else
                    AddLog(lstBox, message);
            };
            // 显示任务日志
            MyLogger.ShowLog = message => ShowLog(this.listBox_JobLog, message);
            MyLogger.Info("加载系统");

            //注册事件
            TaskManager.Instance.mySchedulerListener.OnJobScheduled += new EventHandler<ITriggerEventArgs>(this.OnJobScheduled);
            TaskManager.Instance.mySchedulerListener.OnJobUnscheduled += new EventHandler<TriggerKeyEventArgs>(this.OnJobUnscheduled);

            TaskManager.Instance.mySchedulerListener.OnJobAdded += new EventHandler<IJobDetailEventArgs>(this.OnJobAdded);
            TaskManager.Instance.mySchedulerListener.OnJobDeleted += new EventHandler<JobKeyEventArgs>(this.OnJobDeleted);
            TaskManager.Instance.mySchedulerListener.OnJobPaused += new EventHandler<JobKeyEventArgs>(this.OnJobPaused);
            TaskManager.Instance.mySchedulerListener.OnJobResumed += new EventHandler<JobKeyEventArgs>(this.OnJobResumed);

            TaskManager.Instance.mySchedulerListener.OnSchedulerStarted += new EventHandler<EventArgs>(this.OnSchedulerStarted);
            TaskManager.Instance.mySchedulerListener.OnSchedulerShutdown += new EventHandler<EventArgs>(this.OnSchedulerShutdown);

            try
            {
                SQLiteHelper.CreateDB();
            }
            catch (Exception ex)
            {
                logger.Error("创建数据文件失败：" + ex.Message);
                MessageBox.Show("创建数据文件失败：" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                MyLogger.Info("创建数据文件失败：" + ex.Message);
            }
        }
        private void MainForm_Shown(object sender, EventArgs e)
        {
            Init_Daq();
            Init_Query();
            Init_Query2();
            Init_Export();

            //启动任务
            SetButtonState();
            //自动启动
            metroTile_Start_Click(null, null);
        }
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show("确认退出PLC数据服务系统?", "确认...", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (dialogResult != DialogResult.Yes)
            {
                e.Cancel = true;
            }
        }
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {

        }
        #endregion

        #region 应用
        //private bool isRuning = false;
        private void metroTile_Start_Click(object sender, EventArgs e)
        {
            if (PublicVariable.ynDaq != null)
            {
                metroTile_Start.Enabled = false;
                TaskStart();
            }
        }
        private void metroTile_Stop_Click(object sender, EventArgs e)
        {
            metroTile_Stop.Enabled = false;
            //if (SchedulerManager.Instance.scheduler.IsStarted)
            //{
            //    TaskManager.Instance.PauseAll();
            //}
            //else
            //{

            //}
            TaskStop();
        }
        private void TaskStart()
        {
            try
            {
                GetDataJob.init();
                TaskManager.Instance.TaskStart();
            }
            catch (Exception ex)
            {
                //throw ex;
                MessageBox.Show("开启调度任务失败：" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private void TaskStop()
        {
            try
            {
                if (TaskManager.Instance.taskState != Scheduler.TaskState.Shutdown)
                    TaskManager.Instance.TaskStop();
            }
            catch (Exception ex)
            {
                //throw ex;
                MessageBox.Show("停止调度任务失败:" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


        }
        private void SetButtonState()
        {
            if (TaskManager.Instance.taskState == Scheduler.TaskState.Start)
            {
                metroTile_Start.Enabled = false;
                metroTile_Stop.Enabled = true;
                
                groupBox_daq.Enabled = false;
                groupBox_daq_rule.Enabled = false;

                button_daq_svid_refresh.Enabled = false;
                button_daq_svid_add.Enabled = false;
                button_daq_svid_edit.Enabled = false;
                button_daq_svid_delete.Enabled = false;

            //    //button_Address_Add.Enabled = false;
            //    //button_Address_Edit.Enabled = false;
            //    //button_Address_Delete.Enabled = false;
            }
            else
            {
                metroTile_Start.Enabled = true;
                metroTile_Stop.Enabled = false;

                groupBox_daq.Enabled = true;
                groupBox_daq_rule.Enabled = true;

                button_daq_svid_refresh.Enabled = true;
                button_daq_svid_add.Enabled = true;

                button_daq_svid_edit.Enabled = true;
                button_daq_svid_delete.Enabled = true;
                

            //    //button_Address_Add.Enabled = true;
            //    //button_Address_Edit.Enabled = true;
            //    //button_Address_Delete.Enabled = true;
            }
        }
        private void metroTile_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void metroTile_about_Click(object sender, EventArgs e)
        {
            AboutForm form = new AboutForm();
            DialogResult dialogResult = form.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
            }
        }
        #endregion

        #region home
        /*
         * 显示的图形时间区段长度（小时）
         */
        private int period_hour = 1;

        private void Loadsvid_Home()
        {
            try
            {
                checkedListBox_home.DataSource = PublicVariable.listYnSvid;
                checkedListBox_home.DisplayMember = "name";
                checkedListBox_home.ValueMember = "svid_id";
                //checkedListBox_query_svid.Refresh();

                InitChart();

                //// 显示标签.            
                //// 设置曲线的样式
                //Series series = chart1.Series[0];
                //// 画样条曲线（Spline）
                //series.ChartType = SeriesChartType.Spline;
                //// 线宽2个像素
                //series.BorderWidth = 2;
                //// 线的颜色：红色
                //series.Color = System.Drawing.Color.Red;
                //// 图示上的文字
                //series.LegendText = "演示曲线";
                //// 准备数据 
                //float[] values = { 95, 30, 20, 23, 60, 87, 42, 77, 92, 51, 29 };

                //// 在chart中显示数据
                //int x = 0;
                //foreach (float v in values)
                //{
                //    series.Points.AddXY(x, v);
                //    x++;
                //}

                //// 设置显示范围
                //ChartArea chartArea = chart1.ChartAreas[0];
                //chartArea.AxisX.Minimum = 0;
                //chartArea.AxisX.Maximum = 10;
                //chartArea.AxisY.Minimum = 0d;
                //chartArea.AxisY.Maximum = 100d;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void InitChart()
        {
            home_chartTimer.Interval = 5*1000;//5秒
            home_chartTimer.Start();

        }
        private void chartTimer_Tick(object sender, EventArgs e)
        {
            /*//chart1.ChartAreas[0].AxisX.Minimum = DateTime.Now.AddSeconds(-20).ToOADate();
            //chart1.ChartAreas[0].AxisX.Maximum = DateTime.Now.ToOADate();
            Random ra = new Random();
            Series series = chart1.Series[0];
            series.Points.AddXY(DateTime.Now, ra.Next(10, 90));
            ////chart1.ChartAreas[0].AxisX.ScaleView.Position = series.Points.Count - 5;
            //////throw new NotImplementedException();

            //Random num = new Random();

            //if (++k >= 10)
            //    k = 0;
            //chart1.ChartAreas[0].CursorX.Position = k;
            //chart1.Series[0].Points.RemoveAt(k);

            //yy[k] = (ushort)(num.Next(DateTime.Now.Second));
            //chart1.Series[0].Points.InsertXY(k, k, yy[k]);

            // chart1.Series[0].Points.DataBindXY(xx, yy);
               */

            try
            {
                List<int> listId=new List<int>();
                DateTime dStart1 = Convert.ToDateTime(DateTime.Now.AddHours(-period_hour).ToString("yyyy-MM-dd HH:mm"));//:ss
                double dEnd = dStart1.AddHours(period_hour).ToOADate();// Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).ToOADate();
                double dStart = dStart1.ToOADate();// Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).AddHours(-1).ToOADate();
                double dSeriesLast = dStart;
                foreach (Control _control in this.panel_home_chart.Controls)
                {
                    if (_control is Chart && _control.Tag is YnSvid)
                    {
                        YnSvid _ynSvid = (YnSvid)_control.Tag;
                        Chart chart1 = (Chart)_control;
                        listId.Add(_ynSvid.svid_id);

                        chart1.ChartAreas[0].AxisX.Minimum = dStart;// DateTime.Now.AddSeconds(-20).ToOADate();
                        chart1.ChartAreas[0].AxisX.Maximum = dEnd;// Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).ToOADate();

                        Series seriesValue = chart1.Series[0];
                        Series seriesUpper = chart1.Series[1];
                        Series seriesLower = chart1.Series[2];

                        dSeriesLast = seriesValue.Points[seriesValue.Points.Count - 1].XValue;
                        //删除点
                        for (int i1 = 1; i1 < seriesValue.Points.Count; )
                        {
                            DataPoint dataPoint = seriesValue.Points[i1];
                            if(dataPoint.XValue < dStart)
                            {
                                //seriesValue.CursorX.Position = k;
                                seriesValue.Points.RemoveAt(i1-1);
                                seriesUpper.Points.RemoveAt(i1-1);
                                seriesLower.Points.RemoveAt(i1-1);
                            }
                            else
                            {
                                break;
                            }
                        }

                    }
                }
                //数据查询
                if (listId.Count > 0)
                {
                    DateTime dtStart = DateTime.FromOADate(dSeriesLast);
                    List<YnSvData> listYnSvData = SQLiteHelper.QueryHistoryData(ref dtStart, dStart1.AddHours(period_hour), listId);
                    foreach (YnSvData ynSvData in listYnSvData)
                    {
                        foreach (Control _control in this.panel_home_chart.Controls)
                        {
                            if (_control is Chart && _control.Tag is YnSvid)
                            {
                                YnSvid _ynSvid = (YnSvid)_control.Tag;
                                if (ynSvData.svid_id == _ynSvid.svid_id)
                                {
                                    Chart chart1 = (Chart)_control;
                                    Series seriesValue = chart1.Series[0];
                                    Series seriesUpper = chart1.Series[1];
                                    Series seriesLower = chart1.Series[2];
                                    //增加点
                                    //Random ra = new Random();
                                    //int ra1 = ra.Next(10, 90);
                                    seriesValue.Points.AddXY(ynSvData.createTime.ToOADate(), ynSvData.value);
                                    seriesUpper.Points.AddXY(ynSvData.createTime.ToOADate(), _ynSvid.upper_spec_limit);
                                    seriesLower.Points.AddXY(ynSvData.createTime.ToOADate(), _ynSvid.lower_spec_limit);
                                }
                            }
                        }

                    }
                }

            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
                MyLogger.Info(ex.Message);
            }

        }
        //private List<Chart> chartList = new List<Chart> ();
        private void AddChart(YnSvid ynSvid)
        {

            try
            {
                foreach (Control _control in this.panel_home_chart.Controls)
                {
                    if (_control is Chart && _control.Tag is YnSvid)
                    {
                        YnSvid _ynSvid = (YnSvid)_control.Tag;
                        if (_ynSvid.svid_id == ynSvid.svid_id)
                            return;
                    }
                }

                Chart chart1 = new Chart();
                chart1.Tag = ynSvid;
                ChartArea chartArea1 = new ChartArea();
                Legend legend1 = new Legend();
                Title title1 = new Title();

                chartArea1.AxisX.LabelStyle.Format = "HH:mm";//:ss
                //设置间隔类型           
                chartArea1.AxisX.IntervalType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Minutes;
                chartArea1.AxisX.Interval = 5;
                //chartArea1.AxisX.MajorGrid.Interval = 0D;
                //chartArea1.AxisX.Maximum = 43636.684328703705D;
                //chartArea1.AxisX.Minimum = 43636.64266203704D;
                chartArea1.AxisX.Title = "时间";

                //chartArea1.AxisY.Interval = 10D;
                //chartArea1.AxisY.MajorGrid.Interval = 30D;
                //chartArea1.AxisY.Maximum = 100D;
                chartArea1.AxisY.Minimum = 0D;
                chartArea1.AxisY.Title = "值";
                //chartArea1.Name = "ChartArea1";
                chart1.ChartAreas.Add(chartArea1);

                Series seriesValue = new Series();
                //seriesValue.ChartArea = "ChartArea1";
                seriesValue.ChartType = SeriesChartType.FastLine;
                //seriesValue.XValueType = ChartValueType.Time;
                seriesValue.XValueType = ChartValueType.DateTime;
                //seriesValue.Legend = "Legend1";
                //seriesValue.Name = "Series1";
                seriesValue.LegendText = ynSvid.name;
                chart1.Series.Add(seriesValue);

                Series seriesUpper = new Series();
                seriesUpper.ChartType = SeriesChartType.Line;
                seriesUpper.XValueType = ChartValueType.DateTime;
                seriesUpper.LegendText = "规格上限";
                seriesUpper.Color = Color.Red;
                chart1.Series.Add(seriesUpper);

                Series seriesLower = new Series();
                seriesLower.ChartType = SeriesChartType.Line;
                seriesLower.XValueType = ChartValueType.DateTime;
                seriesLower.LegendText = "规格下限";
                seriesLower.Color = Color.FromArgb(192, 0, 0);//.Red;//192, 0, 0
                chart1.Series.Add(seriesLower);

                chart1.Legends.Add(legend1);
                //chart1.Location = new System.Drawing.Point(0, 0);
                //chart1.Name = "chart2";
                chart1.Size = new System.Drawing.Size(930, 420);
                chart1.TabIndex = 0;
                //chart1.Text = "chart2";

                title1.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F);
                //title1.Name = "Title_Main";
                title1.Text = ynSvid.name;
                chart1.Titles.Add(title1);

                this.panel_home_chart.Controls.Add(chart1);
                chart1.BringToFront();
                chart1.Dock = System.Windows.Forms.DockStyle.Top;

                DateTime dStart1 = Convert.ToDateTime(DateTime.Now.AddHours(-period_hour).ToString("yyyy-MM-dd HH:mm"));//:ss
                double dEnd = dStart1.AddHours(1).ToOADate();// Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).ToOADate();
                double dStart = dStart1.ToOADate();// Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).AddHours(-1).ToOADate();
                chart1.ChartAreas[0].AxisX.Minimum = dStart;// DateTime.Now.AddSeconds(-20).ToOADate();
                chart1.ChartAreas[0].AxisX.Maximum = dEnd;// Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).ToOADate();

                //预置0
                DateTime dt = dStart1;
                seriesValue.Points.AddXY(dt, 0);
                seriesUpper.Points.AddXY(dt, ynSvid.upper_spec_limit);
                seriesLower.Points.AddXY(dt, ynSvid.lower_spec_limit);
                //Random ra = new Random();
                //for (int i1 = 0; i1 < 10; i1++)
                //{
                //    DateTime dt = dStart1.AddMinutes(i1 * 6);
                //    int ra1 = ra.Next(10, 90);
                //    seriesValue.Points.AddXY(dt, ra1);
                //    seriesUpper.Points.AddXY(dt, ynSvid.upper_spec_limit);
                //    seriesLower.Points.AddXY(dt, ynSvid.lower_spec_limit);
                //}
                //chartList.Add(chart1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private void RemoveChart(YnSvid ynSvid)
        {
            try
            {
                Chart chart1 = null;
                foreach (Control _control in this.panel_home_chart.Controls)
                {
                    if (_control is Chart && _control.Tag is YnSvid)
                    {
                        YnSvid _ynSvid = (YnSvid)_control.Tag;
                        if (_ynSvid.svid_id == ynSvid.svid_id)
                        {
                            chart1 = (Chart)_control;
                            break;
                        }
                    }
                }
                if (chart1 != null)
                {
                    this.panel_home_chart.Controls.Remove(chart1);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void checkedListBox_home_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            try
            {
                YnSvid ynSvid = (YnSvid)checkedListBox_home.Items[e.Index];
                if (e.NewValue == CheckState.Checked)
                {
                    AddChart(ynSvid);
                }
                else
                {
                    RemoveChart(ynSvid);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region 数据采集器定义
        //private bool bEditHasChanged_daq = false;
        private void Init_Daq()
        {
            dataGridView_daq_svid.AutoGenerateColumns = false;

            comboBox_daq_com_port.Items.Clear();
            string[] ports = System.IO.Ports.SerialPort.GetPortNames();
            foreach (string port in ports)
            {
                comboBox_daq_com_port.Items.Add(port);
            }

            this.comboBox_dap_commType.SelectedIndexChanged -= new System.EventHandler(this.comboBox_dap_commType_SelectedIndexChanged);

            #region init
            //comboBox_commType.DataSource = System.Enum.GetNames(typeof(YnCommServer.Communication.CommType)).
            //comboBox_commType.DataSource = Enum.GetValues(typeof(YnCommServer.Communication.CommType))
            var listCommType = Enum.GetValues(typeof(Communication.ProtocolType))
                .Cast<Enum>()
                .Select(value => new
                {
                    (Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute).Description,
                    value
                })
                .OrderBy(item => item.value)
                .ToList();
            comboBox_dap_commType.DataSource = listCommType;
            comboBox_dap_commType.DisplayMember = "Description";
            comboBox_dap_commType.ValueMember = "value";
            #endregion

            this.comboBox_dap_commType.SelectedIndexChanged += new System.EventHandler(this.comboBox_dap_commType_SelectedIndexChanged);

            #region Daq
            LoadData_Daq();

            this.button_daq_save.Enabled = false;
            textBox_daq_name.TextChanged += new System.EventHandler(Daq_EditChanged);
            comboBox_dap_commType.SelectedIndexChanged += new System.EventHandler(Daq_EditChanged);
            numericUpDown_daq_intervalInSeconds.ValueChanged += new System.EventHandler(Daq_EditChanged);

            textBox_daq_net_ip.TextChanged += new System.EventHandler(Daq_EditChanged);
            textBox_dap_net_port.TextChanged += new System.EventHandler(Daq_EditChanged);

            comboBox_daq_com_port.SelectedIndexChanged += new System.EventHandler(Daq_EditChanged);
            comboBox_daq_com_baudrate.SelectedIndexChanged += new System.EventHandler(Daq_EditChanged);
            textBox_daq_com_databits.TextChanged += new System.EventHandler(Daq_EditChanged);
            textBox_daq_com_stopbits.TextChanged += new System.EventHandler(Daq_EditChanged);
            comboBox_daq_com_parity.SelectedIndexChanged += new System.EventHandler(Daq_EditChanged);
            textBox_daq_com_station.TextChanged += new System.EventHandler(Daq_EditChanged);
            #endregion

            #region Rule
            comboBox_daq_rule0_svid.SelectedIndexChanged += new System.EventHandler(Daq_EditChanged);
            numericUpDown_daq_rule0_lower.ValueChanged += new System.EventHandler(Daq_EditChanged);
            numericUpDown_daq_rule0_upper.ValueChanged += new System.EventHandler(Daq_EditChanged);
            checkBox_daq_rule0_enabled.CheckedChanged += new System.EventHandler(Daq_EditChanged);

            comboBox_daq_rule1_svid.SelectedIndexChanged += new System.EventHandler(Daq_EditChanged);
            numericUpDown_daq_rule1_trigger_changed.ValueChanged += new System.EventHandler(Daq_EditChanged);
            checkBox_daq_rule1_enabled.CheckedChanged += new System.EventHandler(Daq_EditChanged);
            #endregion

            LoadData_Svid();

        }
        private void LoadData_Daq()
        {
            try
            {
                textBox_dap_net_port.Text = "102";
                comboBox_daq_com_baudrate.Text = "9600";
                textBox_daq_com_databits.Text = "8";
                textBox_daq_com_stopbits.Text = "1";
                textBox_daq_com_station.Text = "2";

                PublicVariable.ynDaq = SQLiteHelper.GetYnDaq(SQLiteHelper.DAQ_ID_1);
                if (PublicVariable.ynDaq != null)
                {
                    textBox_daq_name.Text = PublicVariable.ynDaq.name;
                    Communication.ProtocolType protocolType = Communication.ProtocolType.SiemensPPI;
                    try
                    {
                        protocolType = (Communication.ProtocolType)Enum.Parse(typeof(Communication.ProtocolType), PublicVariable.ynDaq.protocol_type);
                    }
                    catch (Exception) { }
                    comboBox_dap_commType.SelectedValue = protocolType;
                    numericUpDown_daq_intervalInSeconds.Value = PublicVariable.ynDaq.interval_inseconds;

                    //comboBox_dap_commType_SelectedIndexChanged(null, null);
                    textBox_daq_net_ip.Text = PublicVariable.ynDaq.net_ip;
                    if(PublicVariable.ynDaq.net_port==0)
                        textBox_dap_net_port.Text = "102";
                    else
                        textBox_dap_net_port.Text = PublicVariable.ynDaq.net_port.ToString();

                    comboBox_daq_com_port.Text = PublicVariable.ynDaq.com_port;
                    comboBox_daq_com_baudrate.Text = PublicVariable.ynDaq.com_baudrate.ToString();
                    if (PublicVariable.ynDaq.com_databits == 0)
                        textBox_daq_com_databits.Text = "8";
                    else
                        textBox_daq_com_databits.Text = PublicVariable.ynDaq.com_databits.ToString();
                    textBox_daq_com_stopbits.Text = PublicVariable.ynDaq.com_stopbits.ToString();
                    comboBox_daq_com_parity.Text = PublicVariable.ynDaq.com_parity;
                    textBox_daq_com_station.Text = PublicVariable.ynDaq.com_station.ToString();

                }
                //bEditHasChanged_daq = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("读取Daq错误：" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void Daq_EditChanged(object sender, System.EventArgs e)
        {
            //if (ynEditType == YnEditType.Edit || ynEditType == YnEditType.New)
            //{
            //bEditHasChanged_daq = true;
            this.button_daq_save.Enabled = true;
            //}
        }
        private void button_daq_save_Click(object sender, EventArgs e)
        {
            try
            {
                #region Daq
                Communication.ProtocolType protocolType = (Communication.ProtocolType)comboBox_dap_commType.SelectedValue;
                int port = 0;
                if (protocolType == Communication.ProtocolType.SiemensS7Net_1200 
                    || protocolType == Communication.ProtocolType.SiemensS7Net_1500) 
                {
                    System.Net.IPAddress address;
                    if (!System.Net.IPAddress.TryParse(textBox_daq_net_ip.Text.Trim(), out address))
                    {
                        throw new Exception("Ip地址输入不正确！");
                    }
                    if (!int.TryParse(textBox_dap_net_port.Text, out port))
                    {
                        throw new Exception("端口输入错误");
                    }
                }
                if (numericUpDown_daq_intervalInSeconds.Value <= 0)
                {
                    throw new Exception("任务频率应大于0");
                }
                DateTime dtServerTime = DateTime.Now;
                PublicVariable.ynDaq = SQLiteHelper.GetYnDaq(SQLiteHelper.DAQ_ID_1);
                bool isInsert = false;
                if (PublicVariable.ynDaq == null)
                {
                    isInsert = true;
                    PublicVariable.ynDaq = new YnDaq();
                    PublicVariable.ynDaq.createTime = dtServerTime;
                    PublicVariable.ynDaq.daq_id = SQLiteHelper.DAQ_ID_1;
                }
                PublicVariable.ynDaq.updateTime = dtServerTime;
                PublicVariable.ynDaq.name = textBox_daq_name.Text.Trim();

                PublicVariable.ynDaq.protocol_type = protocolType.ToString();
                PublicVariable.ynDaq.interval_inseconds = (int)numericUpDown_daq_intervalInSeconds.Value;

                PublicVariable.ynDaq.net_ip = textBox_daq_net_ip.Text.Trim();
                PublicVariable.ynDaq.net_port = port;

                PublicVariable.ynDaq.com_port = comboBox_daq_com_port.Text;
                int _com_baudrate = 9600;
                int.TryParse(comboBox_daq_com_baudrate.Text, out _com_baudrate);
                PublicVariable.ynDaq.com_baudrate = _com_baudrate;
                int _com_databits = 8;
                int.TryParse(textBox_daq_com_databits.Text, out _com_databits);
                PublicVariable.ynDaq.com_databits = _com_databits;
                int _com_stopbits = 1;
                int.TryParse(textBox_daq_com_stopbits.Text, out _com_stopbits);
                PublicVariable.ynDaq.com_stopbits = _com_stopbits;
                PublicVariable.ynDaq.com_parity = comboBox_daq_com_parity.Text;
                int _com_station = 2;
                int.TryParse(textBox_daq_com_station.Text, out _com_station);
                PublicVariable.ynDaq.com_station = _com_station;

                if (isInsert)
                {
                    SQLiteHelper.Insert(PublicVariable.ynDaq);
                }
                else
                {
                    SQLiteHelper.Update(PublicVariable.ynDaq, new { daq_id = PublicVariable.ynDaq.daq_id });
                }
                #endregion

                #region Rule
                YnSvid ynSvid0 = (YnSvid)comboBox_daq_rule0_svid.SelectedItem;
                YnSvid ynSvid1 = (YnSvid)comboBox_daq_rule1_svid.SelectedItem;
                YnSectionRule ynSectionRule0 = PublicVariable.listYnSectionRule.Find(item => item.rule_id == SQLiteHelper.SECTION_RULE_ID_0);
                YnSectionRule ynSectionRule1 = PublicVariable.listYnSectionRule.Find(item => item.rule_id == SQLiteHelper.SECTION_RULE_ID_1);
                if (ynSectionRule0 == null)
                {
                    ynSectionRule0 = new YnSectionRule();
                    ynSectionRule0.rule_id = SQLiteHelper.SECTION_RULE_ID_0;
                    ynSectionRule0.daq_id = PublicVariable.ynDaq.daq_id;
                    ynSectionRule0.enabled = false;
                    PublicVariable.listYnSectionRule.Add(ynSectionRule0);
                    SQLiteHelper.Insert(ynSectionRule0);
                }
                ynSectionRule0.type = SQLiteHelper.SECTION_RULE_TYPE_Condition;
                ynSectionRule0.svid_id = ynSvid0.svid_id;
                ynSectionRule0.enabled = checkBox_daq_rule0_enabled.Checked;
                if (ynSectionRule0.enabled)
                {
                    if (ynSectionRule0.svid_id == 0)
                    {
                        MessageBox.Show("启用规则变量不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }
                ynSectionRule0.condition_lower_limit = numericUpDown_daq_rule0_lower.Value;
                ynSectionRule0.condition_upper_limit = numericUpDown_daq_rule0_upper.Value;
                if (ynSectionRule1 == null)
                {
                    ynSectionRule1 = new YnSectionRule();
                    ynSectionRule1.rule_id = SQLiteHelper.SECTION_RULE_ID_1;
                    ynSectionRule1.daq_id = PublicVariable.ynDaq.daq_id;
                    ynSectionRule1.enabled = false;
                    SQLiteHelper.Insert(ynSectionRule1);
                    PublicVariable.listYnSectionRule.Add(ynSectionRule1);
                }
                ynSectionRule1.type = SQLiteHelper.SECTION_RULE_TYPE_Trigger;
                ynSectionRule1.svid_id = ynSvid1.svid_id;
                ynSectionRule1.enabled = checkBox_daq_rule1_enabled.Checked;
                if (ynSectionRule1.enabled)
                {
                    if (ynSectionRule1.svid_id == 0)
                    {
                        MessageBox.Show("启用规则变量不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }
                ynSectionRule1.trigger_changed = numericUpDown_daq_rule1_trigger_changed.Value;

                SQLiteHelper.Update(ynSectionRule0, new { rule_id = SQLiteHelper.SECTION_RULE_ID_0 });
                SQLiteHelper.Update(ynSectionRule1, new { rule_id = SQLiteHelper.SECTION_RULE_ID_1 });
                //if (ynSvid == null || ynSvid.svid_id==0)
                //{
                //    //删除规则
                //    if (PublicVariable.ynSectionRule != null)
                //    {
                //        SQLiteHelper.Delete(PublicVariable.ynSectionRule, new { rule_id = PublicVariable.ynSectionRule.rule_id });
                //        PublicVariable.ynSectionRule = null;
                //    }
                //}
                //else
                //{
                //    bool isInsert_Rule = false;
                //    if (PublicVariable.ynSectionRule == null)
                //    {
                //        isInsert_Rule = true;
                //        PublicVariable.ynSectionRule = new YnSectionRule();
                //        PublicVariable.ynSectionRule.rule_id = SQLiteHelper.SECTION_RULE_ID_1;
                //        PublicVariable.ynSectionRule.daq_id = PublicVariable.ynDaq.daq_id;
                //    }
                //    PublicVariable.ynSectionRule.svid_id = ynSvid.svid_id;
                //    PublicVariable.ynSectionRule.save_lower_limit = numericUpDown_daq_rule_lower.Value;
                //    PublicVariable.ynSectionRule.save_upper_limit = numericUpDown_daq_rule_upper.Value;
                //    if (isInsert_Rule)
                //    {
                //        SQLiteHelper.Insert(PublicVariable.ynSectionRule);
                //    }
                //    else
                //    {
                //        SQLiteHelper.Update(PublicVariable.ynSectionRule, new { rule_id = PublicVariable.ynSectionRule.rule_id });
                //    }
                //}


                #endregion

                //bEditHasChanged_daq = false;
                this.button_daq_save.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存Daq错误：" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void comboBox_dap_commType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox_dap_commType.SelectedValue == null)
            {
                return;
            }
            Communication.ProtocolType commType = (Communication.ProtocolType)comboBox_dap_commType.SelectedValue;
            foreach (TabPage tabPage in this.tabControl_daq.TabPages)
            {
                tabControl_daq.TabPages.Remove(tabPage);
            }
            if (commType == Communication.ProtocolType.SiemensPPI)
            {
                tabControl_daq.TabPages.Add(this.tabPage_daq_com);
                tabControl_daq.SelectedTab = tabPage_daq_com;
            }
            else if (commType == Communication.ProtocolType.SiemensS7Net_1200
                || commType == Communication.ProtocolType.SiemensS7Net_1500)
            {
                tabControl_daq.TabPages.Add(this.tabPage_daq_net);
                tabControl_daq.SelectedTab = tabPage_daq_net;
            }
        }
        #endregion

        #region 存储规则定义
        private void LoadData_Rule()
        {
            try
            {
                checkBox_daq_rule0_enabled.Checked = false;
                checkBox_daq_rule1_enabled.Checked = false;
                IList<YnSectionRule> ilistYnSectionRule = SQLiteHelper.Query<YnSectionRule>("select * from YnSectionRule");
                if (ilistYnSectionRule != null)
                {
                    PublicVariable.listYnSectionRule = ilistYnSectionRule.ToList();
                    YnSectionRule ynSectionRule0 = PublicVariable.listYnSectionRule.Find(item => item.rule_id == SQLiteHelper.SECTION_RULE_ID_0);
                    YnSectionRule ynSectionRule1 = PublicVariable.listYnSectionRule.Find(item => item.rule_id == SQLiteHelper.SECTION_RULE_ID_1);
                    if (ynSectionRule0 != null)
                    {
                        comboBox_daq_rule0_svid.SelectedValue = ynSectionRule0.svid_id;
                        numericUpDown_daq_rule0_lower.Value = ynSectionRule0.condition_lower_limit;
                        numericUpDown_daq_rule0_upper.Value = ynSectionRule0.condition_upper_limit;
                        checkBox_daq_rule0_enabled.Checked = ynSectionRule0.enabled;
                    }
                    if (ynSectionRule1 != null)
                    {
                        comboBox_daq_rule1_svid.SelectedValue = ynSectionRule1.svid_id;
                        numericUpDown_daq_rule1_trigger_changed.Value = ynSectionRule1.trigger_changed;
                        checkBox_daq_rule1_enabled.Checked = ynSectionRule1.enabled;
                    }
                }

                //PublicVariable.ynSectionRule = SQLiteHelper.GetYnSectionRule(SQLiteHelper.SECTION_RULE_ID_1);
                //if (PublicVariable.ynSectionRule != null)
                //{
                //    comboBox_daq_rule_svid.SelectedValue = PublicVariable.ynSectionRule.svid_id;

                //    numericUpDown_daq_rule_lower.Value = PublicVariable.ynSectionRule.save_lower_limit;
                //    numericUpDown_daq_rule_upper.Value = PublicVariable.ynSectionRule.save_upper_limit;
                //}
                ////bEditHasChanged_daq = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("读取Daq错误：" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void Init_Rule()
        {
            this.comboBox_daq_rule0_svid.SelectedIndexChanged -= new System.EventHandler(this.Daq_EditChanged);
            this.comboBox_daq_rule1_svid.SelectedIndexChanged -= new System.EventHandler(this.Daq_EditChanged);

            #region init
            YnSvid ynSvid=new YnSvid();
            ynSvid.svid_id = 0;
            ynSvid.name = "";

            List<YnSvid> _listYnSvid0 = new List<YnSvid>();
            _listYnSvid0.Add(ynSvid);
            _listYnSvid0.AddRange(PublicVariable.listYnSvid);

            List<YnSvid> _listYnSvid1 = new List<YnSvid>();
            _listYnSvid1.Add(ynSvid);
            _listYnSvid1.AddRange(PublicVariable.listYnSvid);

            comboBox_daq_rule0_svid.DataSource = _listYnSvid0;
            comboBox_daq_rule0_svid.DisplayMember = "name";
            comboBox_daq_rule0_svid.ValueMember = "svid_id";

            comboBox_daq_rule1_svid.DataSource = _listYnSvid1;
            comboBox_daq_rule1_svid.DisplayMember = "name";
            comboBox_daq_rule1_svid.ValueMember = "svid_id";
            #endregion
            LoadData_Rule();
            this.comboBox_daq_rule0_svid.SelectedIndexChanged += new System.EventHandler(this.Daq_EditChanged);
            this.comboBox_daq_rule1_svid.SelectedIndexChanged += new System.EventHandler(this.Daq_EditChanged);

        }
        #endregion

        #region 状态变量定义
        private void LoadData_Svid()
        {
            try
            {
                IList<YnSvid> ilistYnSvid = SQLiteHelper.Query<YnSvid>("select * from YnSvid order by sortno");
                if (ilistYnSvid != null)
                {
                    PublicVariable.listYnSvid = ilistYnSvid.ToList();
                    YnBaseClass2.YnUc.SortableBindingList<YnSvid> sortableBindingList1 = new YnBaseClass2.YnUc.SortableBindingList<YnSvid>(PublicVariable.listYnSvid);
                    sortableBindingList1.SortDirection = ListSortDirection.Ascending;
                    sortableBindingList1.DefaultSortItem = "sortno";
                    dataGridView_daq_svid.DataSource = sortableBindingList1;
                }
                Loadsvid_Home();
                Loadsvid_Query();
                Loadsvid_Query2();
                Loadsvid_Export();
                Init_Rule();
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载数据错误：" + ex.Message, "错误...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private void button_daq_svid_refresh_Click(object sender, EventArgs e)
        {
            LoadData_Svid();
        }
        private void button_daq_svid_add_Click(object sender, EventArgs e)
        {
            SvidEditForm form = new SvidEditForm();
            form.ynEditType = YnEditType.New;
            DialogResult dialogResult = form.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                ((YnBaseClass2.YnUc.SortableBindingList<YnSvid>)dataGridView_daq_svid.DataSource).Add(form.ynSvid);
                ((YnBaseClass2.YnUc.SortableBindingList<YnSvid>)dataGridView_daq_svid.DataSource).Sort();

                int iFindRow = PublicVariable.listYnSvid.FindIndex(delegate(YnSvid p) { return p.svid_id == form.ynSvid.svid_id; });
                if (iFindRow >= 0)
                    dataGridView_daq_svid.CurrentCell = dataGridView_daq_svid.Rows[iFindRow].Cells[0];


                PublicVariable.listYnSvid = ((YnBaseClass2.YnUc.SortableBindingList<YnSvid>)dataGridView_daq_svid.DataSource).ToList();
                Loadsvid_Home();
                Loadsvid_Query();
                Loadsvid_Query2();
                Loadsvid_Export();
                Init_Rule();

                //
                SetButtonState();
            }
        }
        private void button_daq_svid_edit_Click(object sender, EventArgs e)
        {
           
        }
        private void dataGridView_daq_svid_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            button_daq_svid_edit_Click(null, null);
        }
        private void button_daq_svid_delete_Click(object sender, EventArgs e)
        {
           
        }
        #endregion

        #region 查询
        //private List<YnSvData> listYnSvData_query = new List<YnSvData>();
        private void Init_Query()
        {
            try
            {
                dataGridView_query.AutoGenerateColumns = false;

                //默认查询8个小时
                dateTimePicker_query_end.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:00:00"));
                dateTimePicker_query_start.Value = Convert.ToDateTime(dateTimePicker_query_end.Value.AddHours(-2));
                //checkedListBox_query_svid.

                List<YnSvData> listYnSvData_query = new List<YnSvData>();
                YnBaseClass2.YnUc.SortableBindingList<YnSvData> sortableBindingList1 = new YnBaseClass2.YnUc.SortableBindingList<YnSvData>(listYnSvData_query);
                sortableBindingList1.SortDirection = ListSortDirection.Ascending;
                sortableBindingList1.DefaultSortItem = "createTime";
                dataGridView_query.DataSource = sortableBindingList1;
            }
            catch (Exception ex)
            {
                MessageBox.Show( ex.Message, "错误...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void Loadsvid_Query()
        {
            try
            {
                checkedListBox_query_svid.DataSource = PublicVariable.listYnSvid;
                checkedListBox_query_svid.DisplayMember = "name";
                checkedListBox_query_svid.ValueMember = "svid_id";
                //checkedListBox_query_svid.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private void checkBox_query_all_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                for (int j = 0; j < checkedListBox_query_svid.Items.Count; j++)
                    checkedListBox_query_svid.SetItemChecked(j, checkBox_query_all.Checked);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private void button_query_Click(object sender, EventArgs e)
        {
           

        }
        private void backgroundWorker_query_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                QueryPara queryPara = (QueryPara)e.Argument;//获取RunWorkerAsync(object argument)传入的值
                BackgroundWorker worker = sender as BackgroundWorker;

                //int count = SQLiteHelper.GetHistoryDataCount(queryPara.dtStart, queryPara.dtEnd, queryPara.listId);
                DateTime dtStart = queryPara.dtStart;
                for (; ; )
                {
                    if (worker.CancellationPending)//在耗时操作中判断CancellationPending属性，如果为false则退出
                    {
                        e.Cancel = true;
                        break;
                    }
                    //System.Threading.Thread.Sleep(500);// 模拟耗时的任务
                    List<YnSvData> _list = SQLiteHelper.QueryHistoryData(ref dtStart, queryPara.dtEnd, queryPara.listId);
                    if (dtStart > queryPara.dtEnd)
                    //if (_list.Count == 0)
                    {
                        break;
                    }
                    worker.ReportProgress(_list.Count, _list);// 将触发BackgroundWorker.ProgressChanged事件，向ProgressChanged报告进度
                    Thread.Sleep(10);//1 毫秒 = 0.001 秒
                }
                e.Result = "结束";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private void backgroundWorker_query_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            try
            {
                //e.ProgressPercentage  获取异步操作进度的百分比
                //toolStripProgressBar_query.Value += e.ProgressPercentage;
                if (e.ProgressPercentage + toolStripProgressBar_query.Value < toolStripProgressBar_query.Maximum)
                    toolStripProgressBar_query.Value += e.ProgressPercentage;

                //string state = (string)e.UserState;//接收ReportProgress方法传递过来的userState
                List<YnSvData> _list = (List<YnSvData>)e.UserState;
                //listYnSvData_query.AddRange(_list);
                foreach (YnSvData ynSvData in _list)
                    ((YnBaseClass2.YnUc.SortableBindingList<YnSvData>)dataGridView_query.DataSource).Add(ynSvData);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private void backgroundWorker_query_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //e.Cancelled指示异步操作是否已被取消
            //e.Error 指示异步操作期间发生的错误
            //e.Result 获取异步操作结果的值,即DoWork事件中，Result设置的值。
            if (e.Cancelled == true)
            {
                //resultTextBox.Text += "任务取消。" + "\r\n";
            }
            else if (e.Error != null)
            {
                //resultTextBox.Text += "出现异常: " + e.Error + "\r\n";
            }
            else
            {
                //resultTextBox.Text += "任务完成。 " + "\r\n";
            }
            button_query.Text = "查询";
            toolStripProgressBar_query.Value = 0;
            toolStripProgressBar_query.Maximum = 100;
        }
        private void button_query_chart_Click(object sender, EventArgs e)
        {
           
        }
        #endregion

        #region 查询_对比
        private void Init_Query2()
        {
            try
            {
                dataGridView_query2.AutoGenerateColumns = false;

                //默认查询8个小时
                dateTimePicker_query2_end.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:00:00"));
                dateTimePicker_query2_start.Value = Convert.ToDateTime(dateTimePicker_query_end.Value.AddHours(-2));
                //checkedListBox_query_svid.

                List<YnSvData_hor> listYnSvData_query = new List<YnSvData_hor>();
                YnBaseClass2.YnUc.SortableBindingList<YnSvData_hor> sortableBindingList1 = new YnBaseClass2.YnUc.SortableBindingList<YnSvData_hor>(listYnSvData_query);
                sortableBindingList1.SortDirection = ListSortDirection.Ascending;
                sortableBindingList1.DefaultSortItem = "createTime";
                dataGridView_query2.DataSource = sortableBindingList1;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void Loadsvid_Query2()
        {
            try
            {
                checkedListBox_query2_svid.DataSource = PublicVariable.listYnSvid;
                checkedListBox_query2_svid.DisplayMember = "name";
                checkedListBox_query2_svid.ValueMember = "svid_id";
                //checkedListBox_query_svid.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private void checkBox_query2_all_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                for (int j = 0; j < checkedListBox_query2_svid.Items.Count; j++)
                    checkedListBox_query2_svid.SetItemChecked(j, checkBox_query2_all.Checked);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void checkedListBox_query2_svid_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            try
            {

                //for (int j = 0; j < checkedListBox_query2_svid.Items.Count; j++) 
                //{
                    //checkedListBox_query2_svid.SetItemChecked(j, checkBox_query2_all.Checked);
                //}


                /*YnSvid ynSvid = (YnSvid)checkedListBox_home.Items[e.Index];
                if (e.NewValue == CheckState.Checked)
                {
                    //增加列
                    //AddChart(ynSvid);
                }
                else
                {
                    //RemoveChart(ynSvid);
                }*/
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void button_query2_Click(object sender, EventArgs e)
        {
            

        }
        private void backgroundWorker_query2_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                QueryPara queryPara = (QueryPara)e.Argument;//获取RunWorkerAsync(object argument)传入的值
                BackgroundWorker worker = sender as BackgroundWorker;

                //int count = SQLiteHelper.GetHistoryDataCount(queryPara.dtStart, queryPara.dtEnd, queryPara.listId);
                DateTime dtStart = queryPara.dtStart;
                for (; ; )
                {
                    if (worker.CancellationPending)//在耗时操作中判断CancellationPending属性，如果为false则退出
                    {
                        e.Cancel = true;
                        break;
                    }
                    //System.Threading.Thread.Sleep(500);// 模拟耗时的任务
                    List<YnSvData> _list = SQLiteHelper.QueryHistoryData(ref dtStart, queryPara.dtEnd, queryPara.listId);
                    if (dtStart > queryPara.dtEnd)
                    //if (_list.Count == 0)
                    {
                        break;
                    }
                    worker.ReportProgress(_list.Count, _list);// 将触发BackgroundWorker.ProgressChanged事件，向ProgressChanged报告进度
                    Thread.Sleep(10);//1 毫秒 = 0.001 秒
                }
                e.Result = "结束";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void backgroundWorker_query2_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            try
            {
                //e.ProgressPercentage  获取异步操作进度的百分比
                //toolStripProgressBar_query.Value += e.ProgressPercentage;
                if (e.ProgressPercentage + toolStripProgressBar_query.Value < toolStripProgressBar_query.Maximum)
                    toolStripProgressBar_query.Value += e.ProgressPercentage;

                
                List<YnSvData> _list = (List<YnSvData>)e.UserState;
                var data_timegroup = _list.GroupBy(item => item.createTime);
                foreach (IGrouping<DateTime, YnSvData> data_time in data_timegroup)
                {
                    YnSvData_hor ynSvData_hor = new YnSvData_hor();
                    ynSvData_hor.createTime = data_time.Key;
                    for (int c = 0; c < checkedListBox_query2_svid.CheckedItems.Count; c++)
                    {
                        YnSvid ynSvid = (YnSvid)checkedListBox_query2_svid.CheckedItems[c];
                        foreach (YnSvData ynSvData in data_time)
                        {
                            if (ynSvData.svid_id == ynSvid.svid_id)
                            {
                                var property = ynSvData_hor.GetType().GetProperty("svid_id_" + c);
                                if (property != null)
                                    property.SetValue(ynSvData_hor, ynSvData.value, null);
                                //sLine += "," + ynSvData.value;
                                //ynSvData_hor.createTime = data_time.Key;
                            }
                        }
                    }
                    ((YnBaseClass2.YnUc.SortableBindingList<YnSvData_hor>)dataGridView_query2.DataSource).Add(ynSvData_hor);
                }

                //foreach (YnSvData ynSvData in _list)
                    //((YnBaseClass2.YnUc.SortableBindingList<YnSvData_hor>)dataGridView_query2.DataSource).Add(ynSvData);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void backgroundWorker_query2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //e.Cancelled指示异步操作是否已被取消
            //e.Error 指示异步操作期间发生的错误
            //e.Result 获取异步操作结果的值,即DoWork事件中，Result设置的值。
            if (e.Cancelled == true)
            {
                //resultTextBox.Text += "任务取消。" + "\r\n";
            }
            else if (e.Error != null)
            {
                //resultTextBox.Text += "出现异常: " + e.Error + "\r\n";
            }
            else
            {
                //resultTextBox.Text += "任务完成。 " + "\r\n";
            }
            button_query2.Text = "查询";
            toolStripProgressBar_query.Value = 0;
            toolStripProgressBar_query.Maximum = 100;
        }
        private void button_query2_chart_Click(object sender, EventArgs e)
        {
           
        }
        #endregion

        #region 导出
        //private List<YnSvData> listYnSvData_export = new List<YnSvData>();
        private string exportFile="";
        private int currentSheet = 0;
        private int currentSheetRow = 0;//竖向导出用
        private int currentSheetCol = 0;//横向导出用
        private void Init_Export()
        {
            try
            {
                comboBox_export_filetype.Text = "竖向excel";
                //默认查询8个小时
                dateTimePicker_export_end.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:00:00"));
                dateTimePicker_export_start.Value = Convert.ToDateTime(dateTimePicker_query_end.Value.AddHours(-2));
                checkBox_export_all.Checked = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void Loadsvid_Export()
        {
            try
            {
                checkedListBox_export_svid.DataSource = PublicVariable.listYnSvid;
                checkedListBox_export_svid.DisplayMember = "name";
                checkedListBox_export_svid.ValueMember = "svid_id";
                //checkedListBox_query_svid.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private void checkBox_export_all_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                for (int j = 0; j < checkedListBox_export_svid.Items.Count; j++)
                    checkedListBox_export_svid.SetItemChecked(j, checkBox_export_all.Checked);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void button_export_Click(object sender, EventArgs e)
        {
           
        }
        private void backgroundWorker_export_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                QueryPara queryPara = (QueryPara)e.Argument;//获取RunWorkerAsync(object argument)传入的值
                BackgroundWorker worker = sender as BackgroundWorker;

                //int count = SQLiteHelper.GetHistoryDataCount(queryPara.dtStart, queryPara.dtEnd, queryPara.listId);
                DateTime dtStart = queryPara.dtStart;
                for (; ; )
                {
                    if (worker.CancellationPending)//在耗时操作中判断CancellationPending属性，如果为false则退出
                    {
                        e.Cancel = true;
                        break;
                    }
                    //System.Threading.Thread.Sleep(500);// 模拟耗时的任务
                    List<YnSvData> _list = SQLiteHelper.QueryHistoryData(ref dtStart, queryPara.dtEnd, queryPara.listId);
                    //if (_list.Count == 0)
                    if (dtStart > queryPara.dtEnd)
                    {
                        break;
                    }
                    worker.ReportProgress(_list.Count, _list);// 将触发BackgroundWorker.ProgressChanged事件，向ProgressChanged报告进度
                    Thread.Sleep(50);//1 毫秒 = 0.001 秒
                }
                e.Result = "结束";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void backgroundWorker_export_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            try
            {
                //backgroundWorker_export.CancelAsync();//临时

                //e.ProgressPercentage  获取异步操作进度的百分比
                if (e.ProgressPercentage + toolStripProgressBar_query.Value < toolStripProgressBar_query.Maximum)
                    toolStripProgressBar_query.Value += e.ProgressPercentage;
                //string state = (string)e.UserState;//接收ReportProgress方法传递过来的userState
                List<YnSvData> _list = (List<YnSvData>)e.UserState;
                var data_timegroup = _list.GroupBy(item => item.createTime);

                if (!string.IsNullOrEmpty(exportFile)&&_list.Count > 0)
                {
                    if (comboBox_export_filetype.Text == "txt")
                    {
                        #region txt
                        FileStream fs = null;
                        if (!File.Exists(exportFile))   //判断文件是否存在
                        {
                            fs = new FileStream(exportFile, FileMode.Create);
                        }
                        else
                        {
                            fs = new FileStream(exportFile, FileMode.Append);
                        }
                        string sHeader = "时间";
                        for (int j = 0; j < checkedListBox_export_svid.Items.Count; j++)
                        {
                            if (checkedListBox_export_svid.GetItemChecked(j))
                            {
                                YnSvid ynSvid = (YnSvid)checkedListBox_export_svid.Items[j];
                                sHeader += "," + ynSvid.name;
                            }
                        }
                        byte[] hdata = System.Text.Encoding.Default.GetBytes(sHeader);
                        fs.Write(hdata, 0, hdata.Length);
                        /*方式1:变量竖向写入
                         * //获得字节数组
                        foreach (YnSvData ynSvData in _list)
                        {
                            string sLine = ynSvData.svid_id + "," + ynSvData.svid_name + "," + ynSvData.createTime.ToString("yyyy-MM-dd HH:mm:ss") + "," + ynSvData.value + "\r\n";
                            byte[] data = System.Text.Encoding.Default.GetBytes(sLine);
                            //开始写入
                            fs.Write(data, 0, data.Length);
                        }*/
                        //方式1：变量横向写入
                        foreach (IGrouping<DateTime, YnSvData> data_time in data_timegroup)
                        {
                            //string sLine = data_time.First().createTime.ToString("yyyy-MM-dd HH:mm:ss");
                            string sLine = data_time.Key.ToString("yyyy-MM-dd HH:mm:ss");
                            for (int j = 0; j < checkedListBox_export_svid.Items.Count; j++)
                            {
                                if (checkedListBox_export_svid.GetItemChecked(j))
                                {
                                    YnSvid ynSvid = (YnSvid)checkedListBox_export_svid.Items[j];
                                    foreach (YnSvData ynSvData in data_time)
                                    {
                                        if (ynSvData.svid_id == ynSvid.svid_id)
                                        {
                                            sLine += "," + ynSvData.value;
                                        }
                                    }
                                }
                            }
                            byte[] data = System.Text.Encoding.Default.GetBytes(sHeader);
                            fs.Write(data, 0, data.Length);
                        }

                        //清空缓冲区、关闭流
                        fs.Flush();
                        fs.Close();
                        #endregion
                    }
                    else if (comboBox_export_filetype.Text == "竖向excel"||
                        comboBox_export_filetype.Text == "横向excel")
                    {
                        #region excel
                        IWorkbook wb = null;
                        //FileStream fs = null;
                        if (!File.Exists(exportFile))   //判断文件是否存在
                        {
                            wb = new NPOI.HSSF.UserModel.HSSFWorkbook();
                        }
                        else
                        {
                            FileStream fs = new FileStream(exportFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                            wb = new NPOI.HSSF.UserModel.HSSFWorkbook(fs);
                            fs.Close();
                        }
                        if (comboBox_export_filetype.Text == "竖向excel")
                        {
                            #region 竖向excel
                            //IWorkbook wb = new NPOI.HSSF.UserModel.HSSFWorkbook();
                            ISheet sheet = null;// wb.CreateSheet("Sheet1");
                            //currentSheet = 0;
                            //currentSheetRow = 0;
                            if (currentSheetRow >= 60000)//60000
                            {
                                currentSheetRow = 0;
                                currentSheet++;
                            }
                            if (currentSheetRow == 0)
                            {
                                sheet = wb.CreateSheet("Sheet" + currentSheet);
                                sheet.DefaultRowHeight = 20 * 24;

                                //int iRow = 0;
                                IRow row_title = sheet.CreateRow(currentSheetRow);
                                ICell cell0 = row_title.CreateCell(0);
                                sheet.SetColumnWidth(0, 2000);
                                cell0.SetCellValue("序号");

                                //ICell cell1 = row_title.CreateCell(1);
                                //sheet.SetColumnWidth(1, 4000);
                                //cell1.SetCellValue("变量名称");

                                ICell cell1 = row_title.CreateCell(1);
                                sheet.SetColumnWidth(1, 6000);
                                cell1.SetCellValue("时间");

                                //ICell cell2 = row_title.CreateCell(2);
                                //sheet.SetColumnWidth(2, 4000);
                                //cell2.SetCellValue("值");

                                int icol = 0;
                                for (int j = 0; j < checkedListBox_export_svid.Items.Count; j++)
                                {
                                    if (checkedListBox_export_svid.GetItemChecked(j))
                                    {
                                        icol++;
                                        YnSvid ynSvid = (YnSvid)checkedListBox_export_svid.Items[j];

                                        ICell cell_sv = row_title.CreateCell(1 + icol);
                                        sheet.SetColumnWidth(1 + icol, 4000);
                                        cell_sv.SetCellValue(ynSvid.name);
                                        
                                    }
                                }
                            }
                            else
                            {
                                sheet = wb.GetSheetAt(currentSheet);
                            }

                            /*//获得字节数组
                            foreach (YnSvData ynSvData in _list)
                            {
                                //string sLine = ynSvData.svid_id + "," + ynSvData.svid_name + "," + ynSvData.createTime.ToString("yyyy-MM-dd HH:mm:ss") + "," + ynSvData.value + "\r\n";
                                //byte[] data = System.Text.Encoding.Default.GetBytes(sLine);
                                //开始写入
                                //fs.Write(data, 0, data.Length);
                                currentSheetRow++;
                                IRow rowContent = sheet.CreateRow(currentSheetRow);

                                ICell cellContent0 = rowContent.CreateCell(0);
                                cellContent0.SetCellValue(ynSvData.svid_id);

                                ICell cellContent1 = rowContent.CreateCell(1);
                                cellContent1.SetCellValue(ynSvData.svid_name);

                                ICell cellContent2 = rowContent.CreateCell(2);
                                cellContent2.SetCellValue(ynSvData.createTime.ToString("yyyy-MM-dd HH:mm:ss"));

                                ICell cellContent3 = rowContent.CreateCell(3);
                                cellContent3.SetCellValue(ynSvData.value);
                            }*/
                            foreach (IGrouping<DateTime, YnSvData> data_time in data_timegroup)
                            {
                                currentSheetRow++;
                                IRow rowContent = sheet.CreateRow(currentSheetRow);

                                ICell cellContent0 = rowContent.CreateCell(0);
                                cellContent0.SetCellValue("");

                                ICell cellContent1 = rowContent.CreateCell(1);
                                cellContent1.SetCellValue(data_time.Key.ToString("yyyy-MM-dd HH:mm:ss"));

                                int icol = 0;
                                for (int j = 0; j < checkedListBox_export_svid.Items.Count; j++)
                                {
                                    if (checkedListBox_export_svid.GetItemChecked(j))
                                    {
                                        icol++;
                                        YnSvid ynSvid = (YnSvid)checkedListBox_export_svid.Items[j];

                                        foreach (YnSvData ynSvData in data_time)
                                        {
                                            if (ynSvData.svid_id == ynSvid.svid_id)
                                            {
                                                ICell cellContentj = rowContent.CreateCell(1 + icol);
                                                cellContentj.SetCellValue(ynSvData.value);
                                            }
                                        }
                                    }
                                }
                            }
                            #endregion
                        }
                        else
                        {
                            #region 横向excel
                            ISheet sheet = null;

                            if (currentSheetCol >= 250)//60000
                            {
                                currentSheetCol = 0;
                                //currentSheet++;
                                currentSheetRow ++;
                            }
                            if (currentSheetRow == 0 && currentSheetCol == 0)
                            {
                                sheet = wb.CreateSheet("Sheet" + currentSheet);
                                sheet.DefaultRowHeight = 20 * 24;

                                //currentSheetCol = 0;
                            }
                            else
                            {
                                sheet = wb.GetSheetAt(currentSheet);
                            }
                            IRow row_time = null;
                            List<IRow> row_sv = new List<IRow>();
                            int svid_count = 0;
                            for (int j = 0; j < checkedListBox_export_svid.Items.Count; j++)
                            {
                                if (checkedListBox_export_svid.GetItemChecked(j))
                                {
                                    svid_count++;

                                }
                            }
                            if (currentSheetCol == 0)
                            {
                                row_time = sheet.CreateRow(currentSheetRow * (svid_count+1));
                                int _irow = 0;
                                for (int j = 0; j < checkedListBox_export_svid.Items.Count; j++)
                                {
                                    if (checkedListBox_export_svid.GetItemChecked(j))
                                    {
                                        _irow++;
                                        YnSvid ynSvid = (YnSvid)checkedListBox_export_svid.Items[j];

                                        IRow iRow = sheet.CreateRow(currentSheetRow * (svid_count + 1) + _irow);
                                        row_sv.Add(iRow);

                                    }
                                }
                            }
                            else
                            {
                                row_time = sheet.GetRow(currentSheetRow * (svid_count + 1));
                                int _irow = 0;
                                for (int j = 0; j < checkedListBox_export_svid.Items.Count; j++)
                                {
                                    if (checkedListBox_export_svid.GetItemChecked(j))
                                    {
                                        _irow++;
                                        IRow iRow = sheet.GetRow(currentSheetRow * (svid_count + 1) + _irow);
                                        row_sv.Add(iRow);
                                    }
                                }
                            }


                            if (currentSheetCol == 0)
                            {
                                ICell cell_time = row_time.CreateCell(0);
                                if (currentSheetRow == 0)
                                    sheet.SetColumnWidth(0,4000);
                                cell_time.SetCellValue("时间");

                                int _irow = 0;
                                for (int j = 0; j < checkedListBox_export_svid.Items.Count; j++)
                                {
                                    if (checkedListBox_export_svid.GetItemChecked(j))
                                    {
                                        YnSvid ynSvid = (YnSvid)checkedListBox_export_svid.Items[j];

                                        ICell cell_sv = row_sv[_irow].CreateCell(0);
                                        cell_sv.SetCellValue(ynSvid.name);

                                        _irow++;

                                    }
                                }
                            }

                            foreach (IGrouping<DateTime, YnSvData> data_time in data_timegroup)
                            {
                                currentSheetCol++;

                                ICell cell_time = row_time.CreateCell(currentSheetCol);
                                if (currentSheetRow == 0)
                                    sheet.SetColumnWidth(currentSheetCol, 6000);
                                cell_time.SetCellValue(data_time.Key.ToString("yyyy-MM-dd HH:mm:ss"));

                                int _irow = 0;
                                for (int j = 0; j < checkedListBox_export_svid.Items.Count; j++)
                                {
                                    if (checkedListBox_export_svid.GetItemChecked(j))
                                    {
                                        YnSvid ynSvid = (YnSvid)checkedListBox_export_svid.Items[j];

                                        foreach (YnSvData ynSvData in data_time)
                                        {
                                            if (ynSvData.svid_id == ynSvid.svid_id)
                                            {
                                                ICell cell_sv = row_sv[_irow].CreateCell(currentSheetCol);
                                                cell_sv.SetCellValue(ynSvData.value);

                                            }
                                        }
                                        _irow++;
                                    }
                                }
                            }
                            currentSheetCol += 250;//强制换行
                            #endregion
                        }

                        if (!File.Exists(exportFile))   //判断文件是否存在
                        {
                            FileStream fs = new FileStream(exportFile, FileMode.Create);
                            wb.Write(fs);
                            fs.Close();
                        }
                        else
                        {
                            using (FileStream fs = File.Open(exportFile, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                            {
                                wb.Write(fs);
                                fs.Close();
                            }
                        }
                        #endregion

                    }

                }

                ////写文件
                ////listYnSvData_export.AddRange(_list);
                //foreach (YnSvData ynSvData in _list)
                //    ((YnBaseClass2.YnUc.SortableBindingList<YnSvData>)dataGridView_query.DataSource).Add(ynSvData);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private void backgroundWorker_export_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //e.Cancelled指示异步操作是否已被取消
            //e.Error 指示异步操作期间发生的错误
            //e.Result 获取异步操作结果的值,即DoWork事件中，Result设置的值。
            if (e.Cancelled == true)
            {
                //resultTextBox.Text += "任务取消。" + "\r\n";
                MessageBox.Show("数据导出任务取消", "提示...", MessageBoxButtons.OK, MessageBoxIcon.Stop);

            }
            else if (e.Error != null)
            {
                //resultTextBox.Text += "出现异常: " + e.Error + "\r\n";
                MessageBox.Show("数据导出出现异常", "提示...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                //resultTextBox.Text += "任务完成。 " + "\r\n";
                MessageBox.Show("数据导出任务完成", "提示...", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            button_export.Text = "导出";
            toolStripProgressBar_query.Value = 0;
            toolStripProgressBar_query.Maximum = 100;
        }
        #endregion

        #region 调度任务
        private delegate void delegate_SetButtonState();
        private void OnJobScheduled(object sender, ITriggerEventArgs e)
        {
            //try
            //{
            //    //JobKey jobKey = e.trigger.JobKey;
            //    //MyJobDetail myJobDetail = MyScheduler.Instance.listMyJobDetail.Find(item => item.groupName == jobKey.Group && item.jobName == jobKey.Name);
            //    //if (myJobDetail != null)
            //    //{
            //    //    myJobDetail.taskState = TaskState.Start;
            //    //    this.dataGridView_Scheduler.Refresh();
            //    //}

            //}
            //catch (Exception ex)
            //{
            //    //MessageBox.Show("刷新调度任务显示错误:" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    logger.Error("刷新调度任务显示错误:" + ex.Message);
            //}
        }
        private void OnJobUnscheduled(object sender, TriggerKeyEventArgs e)
        {
            //try
            //{
            //    //ITrigger trigger=SchedulerManager.Instance.scheduler.GetTrigger(e.triggerKey);
            //    //if(trigger!=null)
            //    //{
            //    //    JobKey jobKey = trigger.JobKey;
            //    //    MyJobDetail myJobDetail = MyScheduler.Instance.listMyJobDetail.Find(item => item.groupName == jobKey.Group && item.jobName == jobKey.Name);
            //    //    if (myJobDetail != null)
            //    //    {
            //    //        myJobDetail.taskState = TaskState.Shutdown;
            //    //        this.dataGridView_Scheduler.Refresh();
            //    //    }
            //    //}

            //}
            //catch (Exception ex)
            //{
            //    //throw ex;
            //    //MessageBox.Show("刷新调度任务显示错误:" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    logger.Error("刷新调度任务显示错误:" + ex.Message);
            //}
        }
        private void OnJobAdded(object sender, IJobDetailEventArgs e)
        {
            //try
            //{
            //    IJobDetail jobDetail = e.jobDetail;
            //    MyJobDetail _myJobDetail = MyScheduler.Instance.listMyJobDetail.Find(item => item.groupName == jobDetail.Key.Group && item.jobName == jobDetail.Key.Name);

            //}
            //catch (Exception ex)
            //{
            //    //throw ex;
            //    //MessageBox.Show("刷新调度任务显示错误:" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    logger.Error("刷新调度任务显示错误:" + ex.Message);
            //}
        }
        private void OnJobDeleted(object sender, JobKeyEventArgs e)
        {
            //try
            //{
            //    JobKey jobKey = e.jobKey;
            //    MyJobDetail _myJobDetail = MyScheduler.Instance.listMyJobDetail.Find(item => item.groupName == jobKey.Group && item.jobName == jobKey.Name);

            //}
            //catch (Exception ex)
            //{
            //    //throw ex;
            //    //MessageBox.Show("刷新调度任务显示错误:" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    logger.Error("刷新调度任务显示错误:" + ex.Message);
            //}
        }
        private void OnJobPaused(object sender, JobKeyEventArgs e)
        {
            //try
            //{
            //    JobKey jobKey = e.jobKey;
            //    MyJobDetail _myJobDetail = MyScheduler.Instance.listMyJobDetail.Find(item => item.groupName == jobKey.Group && item.jobName == jobKey.Name);
            //    if (_myJobDetail != null)
            //    {
            //        _myJobDetail.taskState = TaskState.Pause;
            //    }
            //    this.dataGridView_Scheduler.Refresh();
            //    SetSchedulerButtonState(_myJobDetail);
            //}
            //catch (Exception ex)
            //{
            //    //throw ex;
            //    //MessageBox.Show("刷新调度任务显示错误:" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    logger.Error("刷新调度任务显示错误:" + ex.Message);
            //}
        }
        private void OnJobResumed(object sender, JobKeyEventArgs e)
        {
            //try
            //{
            //    JobKey jobKey = e.jobKey;
            //    MyJobDetail _myJobDetail = MyScheduler.Instance.listMyJobDetail.Find(item => item.groupName == jobKey.Group && item.jobName == jobKey.Name);
            //    if (_myJobDetail != null)
            //    {
            //        _myJobDetail.taskState = TaskState.Start;
            //    }
            //    this.dataGridView_Scheduler.Refresh();
            //    SetSchedulerButtonState(_myJobDetail);
            //}
            //catch (Exception ex)
            //{
            //    //throw ex;
            //    //MessageBox.Show("刷新调度任务显示错误:" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    logger.Error("刷新调度任务显示错误:" + ex.Message);
            //}
        }
        private void OnSchedulerStarted(object sender, EventArgs e)
        {
            try
            {
                MyLogger.Info("调度任务启动...");
                delegate_SetButtonState _delegate_SetButtonState = new delegate_SetButtonState(SetButtonState);
                Invoke(_delegate_SetButtonState);
            }
            catch (Exception ex)
            {
                //MessageBox.Show("刷新调度任务显示错误:" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                logger.Error("刷新调度任务显示错误:" + ex.Message);
            }
        }
        private void OnSchedulerShutdown(object sender, EventArgs e)
        {
            try
            {
                MyLogger.Info("调度任务关闭...");
                delegate_SetButtonState _delegate_SetButtonState = new delegate_SetButtonState(SetButtonState);
                Invoke(_delegate_SetButtonState);
            }
            catch (Exception ex)
            {
                //MessageBox.Show("刷新调度任务显示错误:" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                logger.Error("刷新调度任务显示错误:" + ex.Message);
            }
        }
        #endregion

    }
}
